﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using XrmLibrary.ConfigFile;
using XrmLibrary.Configurations;

namespace XrmLibrary.Adapters
{
    public class AdapterRuntimeLoader
    {
        private const String CrmConfigurationTypeSubName = "Configurations.CrmConfiguration";
        private const String CrmDiscoveryServiceAdapterTypeSubName = "Adapters.DiscoveryServiceAdapter";
        private const String CrmOrganizationServiceAdapterTypeSubName = "Adapters.OrganizationServiceAdapter";

        private readonly String _assemblyNameAndExtension;
        private readonly String _assemblyName;
        private readonly String _crmConfigurationTypeName;

        private AdapterRuntimeLoader(String assemblyName, String assemblyNameAndExtension)
        {
            _assemblyNameAndExtension = assemblyNameAndExtension;
            _assemblyName = assemblyName;
            _crmConfigurationTypeName = BuildFullTypeName(CrmConfigurationTypeSubName);
        }

        private String BuildFullTypeName(String typeSubName)
        {
            return String.Format("{0}.{1}", _assemblyName, typeSubName);
        }

        public static AdapterRuntimeLoader Instantiate(String assemblyName, String assemblyNameAndExtension)
        {
            return new AdapterRuntimeLoader(assemblyName, assemblyNameAndExtension);
        }

        public CrmConfigurationBase InstantiateCrmConfiguration(AdapterConfiguration adapterConfig)
        {
            Assembly assembly = Assembly.LoadFrom(_assemblyNameAndExtension);
            Type type = assembly.GetType(_crmConfigurationTypeName);
            CrmConfigurationBase crmConfiguration = CreateInstanceOf<CrmConfigurationBase>(type);
            crmConfiguration.Instantiate(adapterConfig);
            return crmConfiguration;
        }

        private static T CreateInstanceOf<T>(Type type)
        {
            return (T) Activator.CreateInstance(type);
        }
    }
}
